﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.Infrastructure;
using Microsoft.Practices.Unity;
using System.Reflection;
using System.Data.Entity;

namespace Framework.Config
{
    public static class FrameworkConfigurationExtension
    {
        public static Configuration RegisterIdentityGenerator(this Configuration configuration, IEnumerable<string> names)
        {
            var dbContext = IoCFactory.Resolve<DbContext>("DomainModelContext");
           
            List<string> tableNames = new List<string>();
            tableNames.Add("Global");
            if (names != null && names.Count() > 0)
            {
                tableNames.AddRange(names);
            }
            tableNames.ForEach(name =>
            {
                var sql = new StringBuilder().Append("SET QUOTED_IDENTIFIER ON\r\n");
                sql.AppendFormat("if object_id('[{0}Identities]') is null ", name)
                   .AppendFormat("CREATE TABLE [{0}Identities]( ", name)
                   .Append("[ID] [int] IDENTITY(1,1) NOT NULL, ")
                   .AppendFormat("CONSTRAINT [PK_dbo.{0}Identities] PRIMARY KEY CLUSTERED ", name)
                   .Append("([ID] ASC" )
                   .Append(")WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] ")
                   .Append(") ON [PRIMARY]");
                      
                   dbContext.Database.ExecuteSqlCommand(sql.ToString());
            });
            
            return configuration;
        }
    }
}
